package com.autoplaza;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class Compartir extends Activity implements Runnable{
	ProgressDialog pd;
	String idanuncio,nombrerecibe,emailrecibe,nombreenvia,emailenvia,mensaje,result, cadena,foto,urlcorta;
	EditText txtnomrecibe,txtnomenvia,txtemailrecibe,txtemailenvia,txtmensaje;
	Button enviar,compartirpor;
	InputStream is = null;
	private ProgressDialog progressDialog;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.compartir);
		
		int size = Utils.getScreenSize2(Compartir.this);
		if( size == 1){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(30, 30));
		}		
		if( size == 2){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60));	
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(45, 45));

		}		
		if( size == 3){
			RelativeLayout lin = (RelativeLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 80));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(80, 80));

		}
		
		Bundle extras=getIntent().getExtras();
		if(extras != null){
			idanuncio=extras.getString("idanuncio");
			txtemailenvia=(EditText) findViewById(R.id.emailenvia);
			txtemailrecibe=(EditText) findViewById(R.id.emailrecibe);
			txtnomenvia=(EditText) findViewById(R.id.nombreenvia);
			txtnomrecibe=(EditText) findViewById(R.id.nombrerecibe);
			txtmensaje=(EditText) findViewById(R.id.comentarios);
			enviar=(Button) findViewById(R.id.enviaremail);
			compartirpor=(Button) findViewById(R.id.compartirpor);
			cadena = extras.getString("cadena");
			foto = extras.getString("foto");
			
			enviar.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(isNetwork()==true){
						if(txtemailenvia.getText().toString().equals("")||txtemailrecibe.getText().toString().equals("")||txtnomenvia.getText().toString().equals("")||txtnomrecibe.getText().toString().equals("")||txtmensaje.getText().toString().equals("")){
							AlertDialog.Builder builder = new AlertDialog.Builder(Compartir.this);
							builder.setMessage("Datos faltantes")
							       .setCancelable(false)
							       .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
							           public void onClick(DialogInterface dialog, int id) {
							                // put your code here
							           }
							       });
							       
							AlertDialog alertDialog = builder.create();
							alertDialog.show();
						}
						else{
							progreso();
						}
					}else{
						dialogoInternet();
					}

					
				}
			});
			compartirpor.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					if(isNetwork()==true){
						shareit(cadena);
					}else{
						dialogoInternet();
					}
					
				}
			});
			
			
		}
	}
	
	void progreso(){
		pd=ProgressDialog.show(this, "Espere por favor...", "Buscando...");
		Thread thread=new Thread(this);
		thread.start();
		
	}
	
	Handler handler=new Handler(){
		
		public void handleMessage(android.os.Message msg) {
			Toast.makeText(getApplicationContext(), "Mensaje enviado correctamente", Toast.LENGTH_SHORT).show();
			pd.dismiss();
			pd.cancel();
			txtemailenvia.setText("");
			txtemailrecibe.setText("");
			txtmensaje.setText("");
			txtnomenvia.setText("");
			txtnomrecibe.setText("");
			
		};
		
	};
	
	protected void enviarMail() {
		
        InputStream is = null;
        
		try {
			nombrerecibe=URLEncoder.encode(txtnomrecibe.getText().toString(), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
			emailrecibe=txtemailrecibe.getText().toString().trim();

		try {
			nombreenvia=URLEncoder.encode(txtnomenvia.getText().toString(), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		emailenvia=txtemailenvia.getText().toString().trim();
		
		try {
			mensaje=URLEncoder.encode(txtmensaje.getText().toString(), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	
		
		try{
		String url="http://www7.autos-usados.autoplaza.com.mx/systems/autos/xtSendToFriendBlack.asp?AnuncioID="+idanuncio+
													"&NombreRecibe="+nombrerecibe+
													"&EmailRecibe="+emailrecibe+
													"&NombreEnvia="+nombreenvia+
													"&EmailEnvia="+emailenvia+
													"&Mensaje="+mensaje;
		
		Log.i("URL", ""+url);

		URI myURI = null;
		try {
			myURI = new URI(url);
		} catch (URISyntaxException e) {
		}
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet getMethod = new HttpGet(myURI);
		HttpResponse webServerResponse = null;
		try {
			webServerResponse = httpClient.execute(getMethod);
		} catch (ClientProtocolException e) {
		} catch (IOException e) {
		}
		
		HttpEntity httpEntity = webServerResponse.getEntity();
		
		if (httpEntity != null) {
			try {
				is = httpEntity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
	            StringBuilder sb = new StringBuilder();
	            String line = null;
	            while ((line = reader.readLine()) != null) {
	                    sb.append(line + "\n");
	            }
	            is.close();
	            result=sb.toString();

			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		
		}catch (Exception e) {
		}
		
		handler.sendEmptyMessage(0);
	}
	@Override
	public void run() {
		enviarMail();
	}
	protected void shareit(String cadena) {
		downloadBitmapImage();
		Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
		sharingIntent.setType("image/*");
		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, ""+cadena);
		sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "autoplaza.com.mx");

//		sharingIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//		sharingIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
//		sharingIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file:///"+Environment.getExternalStorageDirectory()+"/shareimage.png"));
		sharingIntent.putExtra(Intent.EXTRA_STREAM,
				Uri.fromFile(new File(Environment.getExternalStorageDirectory()+"/shareimage.png")));

		
		startActivity(Intent.createChooser(sharingIntent, "Compartir mediante"));
	}
	
    public boolean isNetwork(){
		NetworkInfo networkInfo = ((ConnectivityManager) getApplicationContext()
	              .getSystemService(Context.CONNECTIVITY_SERVICE))
	              .getActiveNetworkInfo();

	            if(networkInfo == null || !networkInfo.isConnected()) {
	             return false;
	            }
	            return true;
    }
    
	private void dialogoInternet() {
		AlertDialog.Builder builder = new AlertDialog.Builder(Compartir.this);
		builder.setMessage("Necesita conexión a Internet")
		       .setCancelable(false)
		       .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		           }
		       });
		AlertDialog alertDialog = builder.create();
		alertDialog.show();		
								
	}
	
	 void downloadBitmapImage()
	    {
	        InputStream input;
	        try {
	            URL url = new URL (""+foto);
	            input = url.openStream();
	            byte[] buffer = new byte[1500];
	            OutputStream output = new FileOutputStream (Environment.getExternalStorageDirectory()+"/shareimage.png");
	            try 
	            {     
	                int bytesRead = 0;
	                while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) 
	                {
	                    output.write(buffer, 0, bytesRead);
	                }
	            } 
	            finally 
	            {
	                output.close();
	                buffer=null;
	            }
	        } 
	        catch(Exception e) 
	        {
	            Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
	        }
	    }
	 
	 

	
}
